<?php
namespace app\houtai\controller\system;
use app\houtai\controller\BaseController;
use think\db\Expression;
use Exception;

class ChannelController extends BaseController {
  /**
   *  @brief  : 渠道查询
   *  @return : page
   *  @details:
   */
  public function indexAction() {
    $list = table('CYBasicDB.dbo.ChannelConfig a', 'rydb.basic')->field([
      'a.*',
      'ISNULL(b.Total, 0)' => 'TotalPlayer',
      'ISNULL(c.Total, 0)' => 'TotalAgent',
      'ISNULL(d.Total, 0)' => 'TotalGame',
      'ISNULL(e.Total, 0)' => 'TotalVersion',
    ])
    ->join('(SELECT Channel, COUNT (Channel) AS Total FROM CYBasicDB.dbo.AccountsInfo WHERE AccountsType = 0 GROUP BY Channel, AccountsType) b', 'b.Channel = a.ID', 'LEFT')
    ->join('(SELECT Channel, COUNT (Channel) AS Total FROM CYBasicDB.dbo.AccountsInfo WHERE AccountsType = 1 GROUP BY Channel, AccountsType) c', 'c.Channel = a.ID', 'LEFT')
    ->join('(SELECT ID, COUNT(ID) AS Total FROM CYBasicDB.dbo.ChannelConfig WHERE State = 1 GROUP BY ID) d', 'd.ID = a.ID', 'LEFT')
    ->join('(SELECT Channel, COUNT(Channel) AS Total FROM CYRecordDB.dbo.GameChannelVersion GROUP BY Channel) e', 'e.Channel = a.ID', 'LEFT')
    ->order('ID')->paginate();
    return $this->fetch('', ['list' => $list]);
  }
  /**
   *  @brief  : 渠道详情
   *  @return : page|JSON
   *  @details:
   */
  public function detailAction() {
    $id = $this->request->param('id/d', 0);
    $Channel = table('ChannelConfig', 'rydb.basic')->where(['ID' => $id])->find();
    if ($this->request->isGet()) {
      return $this->fetch('', ['row' => $Channel ?? ['ID'=>0]]);
    }
    if ($this->request->isPost()) {
      if (empty($Channel)) {
         //新建
          $data=[
              'ID'=>$this->request->param('ChannelID/d', 0),
              'Name'=>$this->request->param('ChannelName/s','新建渠道'),
          ];
          if ($data['ID'] <= 0) {
              return result([], 100, '欲修改的渠道不存在');
          }else{
              $eax =  table('ChannelConfig', 'rydb.basic')->insert($data);
              return result([], 0,'创建成功');
          }
          
      }
        $data = [
            'State'  => $this->request->param('State/d' , 0),
            'ZCGold' => $this->request->param('ZCGold/d', 0),
            'SMGold' => $this->request->param('SMGold/d', 0),
            'FXGold' => $this->request->param('FXGold/d', 0),
            'BDGold' => $this->request->param('BDGold/d', 0),
            'Remark' => $this->request->param('Remark/S',''),
            'ZCRoomCard' => $this->request->param('ZCRoomCard/d', 0),
            'SMRoomCard' => $this->request->param('SMRoomCard/d', 0),
            'FXRoomCard' => $this->request->param('FXRoomCard/d', 0),
            'BDRoomCard' => $this->request->param('BDRoomCard/d', 0),
            'LuckyWheelCostCoin'=>$this->request->param('lwcc/d', 0),
            'LuckyWheelFreeCount'=>$this->request->param('lwfc/d', 0),
        ];
        //--- 验证器验证 ---
        $retn = $this->validate($data, [ // 按照顺序逐一判断
            'LuckyWheelFreeCount|幸运转盘每日免费次数' => 'require|egt:0',
            'LuckyWheelCostCoin|幸运转盘单次消耗金币'  => 'require|egt:0',
            'ZCRoomCard|注册赠送房卡'   => 'require|egt:0',
            'SMRoomCard|实名赠送房卡'   => 'require|egt:0',
            'FXRoomCard|分享赠送房卡'   => 'require|egt:0',
            'BDRoomCard|绑定赠送房卡'   => 'require|egt:0',
            'ZCGold|注册赠送金币'   => 'require|egt:0',
            'SMGold|实名赠送金币'   => 'require|egt:0',
            'FXGold|分享赠送金币'   => 'require|egt:0',
            'BDGold|绑定赠送金币'   => 'require|egt:0',
            'Remark|渠道备注'   => 'require|max:50',
        ]);
        if (true !== $retn) {
            return result([], 100, $retn);
        }
      $data['UpdateTime']   = new Expression('GETDATE()');    //修改时间
      //修改
      $eax = table('ChannelConfig', 'rydb.basic')->where('ID', $id)->update($data);
     
      return result([], 0);
    }
  }
    /**
     *  @brief  : 网络配置详情
     *  @return : JSON
     *  @details:
     */
  public function srvdetailAction(){
      $id = $this->request->param('id/d', 0);
      $Channel = table('ChannelConfig', 'rydb.basic')->where(['ID' => $id])->find();
      $data['ID'] = $Channel['ID'];
      $data['Name'] = $Channel['Name'];
      $data['CreateTime'] = $Channel['CreateTime'];
      $data['UpdateTime'] = $Channel['UpdateTime'];
      $data['Server0'] = json_decode($Channel['Server0'],true);
      $data['Server1'] = json_decode($Channel['Server1'],true);
      $data['Server2'] = json_decode($Channel['Server2'],true);
      $data['Server3'] = json_decode($Channel['Server3'],true);
      if ($this->request->isGet()) {
          return $this->fetch('', ['row' => $data ?? []]);
      }
      if ($this->request->isPost()) {
          $data = $this->request->param();
          unset($data['id']);
          foreach ($data as $k=>$c){
              $str = substr($k,0,4);
              if($str == 'Srv0'){
                  $srv[0][$k] = $c;
              }else if ($str == 'Srv1'){
                  $srv[1][$k] = $c;
              }else if ($str == 'Srv2'){
                  $srv[2][$k] = $c;
              }else if ($str == 'Srv3'){
                  $srv[3][$k] = $c;
              }
          }
          for ($j=0; $j <count($srv) ; $j++) {
              for($i=0;$i<(count($srv[$j]));$i++){
                  foreach ($srv[$j] as $key => $value) {
                      if (substr($key, -1,1) == $i/2-1) {
                          if       (substr($key, -3,2) == "IP") {//SERVERIP
                              $data[$j]['ServerConfig'][$i/2-1]['ServerIP'] = $value;
                          }else if (substr($key, -3,2) == "Ad") {//SERVERAD

                              $data[$j]['ServerConfig'][$i/2-1]['ServerPort'] = $value;
                          }else if (substr($key, -2,2) == "IP") {//LOGIP

                              $data[$j]['LogConfig']['LogIP'] = $value;
                          }else if (substr($key, -2,2) == "Ad") {//LOGAD

                              $data[$j]['LogConfig']['LogPort'] = $value;
                          }
                      }
                  }
              }
              $data[$j] = json_encode($data[$j]);
          }
          $res = [
              "Server1" => $data[1],
              "Server2" => $data[2],
              "Server3" => $data[3],
              "Server0" => $data[0],
              "UpdateTime" => new Expression('GETDATE()'),
          ];
          $re = table('ChannelConfig','rydb.basic')->where('ID',$id)->update($res);
          return result([],0);

      }
  }

    /**
     *  @brief  : 渠道版本管理
     *  @return : JSON
     *  @details:
     */
    public function VersionAction(){
      $list = table('CYBasicDB.dbo.ChannelConfig a', 'rydb.basic')->field([
      'a.*',
      'ISNULL(d.Total, 0)' => 'TotalGame',
      'ISNULL(e.Total, 0)' => 'TotalVersion',
    ])
    ->join('(SELECT ID, COUNT(ID) AS Total FROM CYBasicDB.dbo.ChannelConfig WHERE State = 1 GROUP BY ID) d', 'd.ID = a.ID', 'LEFT')
    ->join('(SELECT Channel, COUNT(Channel) AS Total FROM CYRecordDB.dbo.GameChannelVersion GROUP BY Channel) e', 'e.Channel = a.ID', 'LEFT')
    ->where(['State' => 1])->order('ID')->paginate();
    return $this->fetch('', ['list' => $list]);

    }

    /**
     *  @brief  : 渠道版本管理
     *  @return : JSON
     *  @details:
     */
    public function DelchannelAction(){
        $id = $this->request->param('id/d',0);

        if ($id <= 0) {
            return result([],101,'参数错误');
        }
        //删除basic库该渠道用户
        table("AccountsInfo","rydb.basic")->where("Channel",$id)->delete();
        table("AccountsBackpack","rydb.basic")->where("Channel",$id)->delete();
        table("AccountsExtension","rydb.basic")->where("Channel",$id)->delete();
        table("AccountsGameCurrency","rydb.basic")->where("Channel",$id)->delete();
        table("AccountsGameLogo","rydb.basic")->where("Channel",$id)->delete();
        table("ChannelConfig","rydb.basic")->where("ID",$id)->delete();
        table("GameActivity","rydb.basic")->where("Channel",$id)->delete();
        table("UserOnline","rydb.basic")->where("Channel",$id)->delete();
        //删除record库该渠道的数据
        table("AccountsMessage","rydb.record")->where("Channel",$id)->delete();
        table("CostRoomCardRecord","rydb.record")->where("Channel",$id)->delete();
        table("GameChannelVersion","rydb.record")->where("Channel",$id)->delete();
        table("RecordCreateTable","rydb.record")->where("Channel",$id)->delete();
        table("RecordGameData","rydb.record")->where("Channel",$id)->delete();
        table("RecordGameDataChild","rydb.record")->where("Channel",$id)->delete();
        table("RecordGameDataUserRecord","rydb.record")->where("Channel",$id)->delete();
        table("RecordUserLoginLog","rydb.record")->where("Channel",$id)->delete();
        table("SysMessage","rydb.record")->where("Channel",$id)->delete();
        return result([],0);
    }
}
